package ljl.alg.wangzheng_camp.round1.tree;

public class _offer36_tree_to_double_list {
    
    /**
     * 真几把傻逼
     * 写了一个小时，最后栈溢出？？？？
     *
     * 哎我去？写了俩小时，过了！
     *
     * 但是我可没骄傲啊，我没骄傲
     *
     * */
    public Node treeToDoublyList(Node root) {
        if (root == null) return null;
        Node left = treeToDoublyList(root.left);
        Node right = treeToDoublyList(root.right);
        
        Node newHead = null;
        if (left != null) {
            newHead = left;
            Node leftEnd = left.left;
            leftEnd.right = root;
            root.left = leftEnd;
            left.left = root;
            root.right = left;
        }
        if (newHead == null) {
            newHead = root;
            newHead.left = newHead.right = root;
        }
        
        if (right != null) {
            Node rightEnd = right.left;
            rightEnd.right = newHead;
            newHead.left = rightEnd;
            root.right = right;
            right.left = root;
        }
        
        return newHead;
    }
    
    /**
     * 这个解法非常的好，比我那个好
     * 比我那个好想
     * 我那个也不是我的，是东逼的
     * */
    Node pre, head;
    public Node treeToDoublyList2(Node root) {
        if (root == null) return null;
        dfs(root);
        head.left = pre; pre.right = head;
        return head;
    }
    void dfs(Node node) {
        if (node == null) return;
        dfs(node.left);
        if (pre != null) pre.right = node;
        else head = node;
        node.left = pre;
        pre = node;
        dfs(node.right);
    }
    
    class Node {
        public int val;
        public Node left;
        public Node right;
        
        public Node() {}
        
        public Node(int _val) {
            val = _val;
        }
        
        public Node(int _val,Node _left,Node _right) {
            val = _val;
            left = _left;
            right = _right;
        }
    }
}
